# 从flask框架中导⼊Flask类
import os

from flask import Flask, request

import core

# 传⼊__name__初始化⼀个Flask实例
app = Flask(__name__)


@app.route('/login')
def login():
    userPhone = request.args.get('phone')
    userPwd = request.args.get('pwd')
    duration = request.args.get('duration')

    if not userPhone or not userPwd:
        empty = {"Status": "-1", "Message": "缺少参数"}
        return empty

    if not duration:
        duration = 30

    result = core.login(userPhone, userPwd, duration=duration)
    resultJson = {"Status": "0", "Message": result}
    return resultJson

#查询资产
@app.route('/queryAssetAndPosition')
def queryAssetAndPosition():
    token = request.headers.get("token", "")
    if not token:
        empty = {"Status": "-1", "Message": "token不可为空"}
        return empty

    result = core.query_asset_and_position(token)
    return result

#当日委托
@app.route('/queryOrders')
def queryOrders():
    token = request.headers.get("token", "")
    if not token:
        empty = {"Status": "-1", "Message": "token不可为空"}
        return empty

    result = core.query_orders(token)
    return result


#当日成交
@app.route('/queryTrades')
def queryTrades():
    token = request.headers.get("token", "")
    if not token:
        empty = {"Status": "-1", "Message": "token不可为空"}
        return empty

    result = core.query_trades(token)
    return result

"""
交易接口, 买入或卖出
:param str stock_code: 股票代码
:param str trade_type: 交易方向  B for buy, S for sell
:param str market: 股票市场,HA 上海, SA
:param float price: 股票价格
:param int amount: 买入/卖出数量
"""
@app.route('/createOrder')
def createOrder():
    token = request.headers.get("token", "")
    if not token:
        empty = {"Status": "-1", "Message": "token不可为空"}
        return empty

    stock_code = request.args.get('stock_code')
    trade_type = request.args.get('trade_type')
    market = request.args.get('market')
    price = request.args.get('price')
    amount = request.args.get('amount')

    if not stock_code or not trade_type or not market or not price or not amount:
        empty = {"Status": "-1", "Message": "缺少参数"}
        return empty

    result = core.create_order(token=token, stock_code=stock_code, trade_type=trade_type, market=market, price=price, amount=amount)
    return result

"""取消交易接口.
:param str order_str: 订单字符串
"""
@app.route('/cancelOrder')
def cancelOrder():
    token = request.headers.get("token", "")
    if not token:
        empty = {"Status": "-1", "Message": "token不可为空"}
        return empty

    order_str = request.args.get('order_str')
    if not order_str:
        empty = {"Status": "-1", "Message": "缺少参数"}
        return empty

    result = core.cancel_order(token=token, order_str=order_str)
    return result


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)
